define(["moment"], function (moment) {
	return ["$scope", "$filter", "$stateParams", "config", "MMWService","$mdDialog",
	function ($scope, $filter, $stateParams, config, $MMWService,$mdDialog) {
		$scope.init = function(){
			//每隻程式都有，等於window.onload方法
			$scope.C00_require_condition = true;
			var datasource_format_info = {};
			datasource_format_info.iselectd_filed = "0";
			datasource_format_info.column_info = [$filter('translate')('B0801.js.condition.column_1'),$filter('translate')('B0801.js.condition.column_2')];
			datasource_format_info.data_info = [[0,$filter('translate')('B0801.js.condition.state_0')],[1,$filter('translate')('B0801.js.condition.state_1')]];
            $scope.codeList = [
                {name:$filter('translate')('B0801.js.condition.code_1'), column_name:'A.ACCESSORYNO'},
                {name:$filter('translate')('B0801.js.condition.code_2'), column_name:'A.ACCESSORYSTATE', data_type:'S',datasource_format_info:datasource_format_info}
			];
			$scope.acc_data = [];
			$scope.select_all = false;
			$scope.is_inject = false;
			$scope.mode = "query";
			$scope.printList = []; // 列印詳情
		}
		
		$scope.back = function(){
            //返回首頁，傳入true表示使用退出
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);//動畫
		}
		
		$scope.confirm = function(){
			//確認按鈕
			var select_data = $filter('filter')($scope.acc_data,{is_select:1});
			console.log(select_data);
			if(select_data.length > 0)
			{
				$mdDialog.dialog('module/moduleB/program/B08/B0801/B0801_detail.html',acc_detail_dialog_controller);
			}
			else
			{
				$scope.$root.showAlert($filter('translate')('B0801.js.alert.error_0'));
			}
            /*$scope.$root.hideMenu();
			$scope.$root.changeProgram('home', true); */
		}
		function acc_detail_dialog_controller(dialog)
		{
			var controller = 
			{
				select_user_acc:"",
				select_date_now:new Date(),
				select_company_no:"",
				select_description:"",
				select_reasion:[],
				init:function()
				{
					dialog.select_user_acc  = config.cache.account;
					dialog.select_date_now = new Date();
					dialog.elect_company_no ="";
					dialog.select_description ="";
					dialog.select_reasion = [];
				},
				load_acc:function()
				{
					$MMWService.showQueryListPNIG({
						page_mode:44,
						header: [
							{label:$filter('translate')('B0801.js.user_list.column_1'), code:'page_no'},
							{label:$filter('translate')('B0801.js.user_list.column_2'), code:'page_name'},
							{label:$filter('translate')('B0801.js.user_list.column_3'), code:'page_desc', width:'110px'}
						],
						setCondition:function(conditions){
							return conditions;
						},
						selectCode:dialog.select_user_acc,
						confirm : function(selectItem){
							dialog.select_user_acc = selectItem.page_no;
						}
					});
				},
				load_manufacturer:function()
				{
					$MMWService.showQueryListPNIG({
						page_mode: 10,
						condition: [
							{name:$filter('translate')('B0216.queryList.column1_1'), column_name:'SubcontractorNo', query_mode:'2', value:''}
						],
						header: [
							{label:$filter('translate')('B0216.queryList.column1_1'), code:'page_no'},
							{label:$filter('translate')('B0216.queryList.column1_1'), code:'page_name'}
						],
						confirm : function(selectItem){
							dialog.select_company_no = selectItem.page_no;
						}
					});
				},
				load_reasion:function()
				{
					$MMWService.showQueryListPNIG({
						page_mode: 31,
						key:'page_no',
						header: [
							{label:$filter('translate')('B0801.js.reasion_list.column_1'), code:'page_no'},
							{label:$filter('translate')('B0801.js.reasion_list.column_2'), code:'page_name'}
						],
						setCondition:function(conditions){
							conditions.push(
								{column_name:'ReasonType', query_mode:0, value: '1', merge_condition_model:'AND'},
								{column_name:'ISSUESTATE', query_mode:0, value: '2', merge_condition_model:'AND'}
							);
							return conditions;
						},
						confirm : function(selectItem){
							var obj ={};
							obj.reasion_no = selectItem.page_no;
							obj.reasion_name = selectItem.page_name;
							var has_data = $filter('filter')(dialog.select_reasion,obj);
							if(has_data.length <= 0)
							{
								dialog.select_reasion.push(obj);
							}
						}
					});
				},
				remove_reasion:function(index,item)
				{
					dialog.select_reasion.splice(index, 1);
				},
				back: function () 
				{
					dialog.hide();
				},
				confirm: function () 
				{
					var select_data = $filter('filter')($scope.acc_data,{is_select:1});	
					if(select_data.length <= 0)
						return $scope.$root.showAlert($filter('translate')('B0801.js.alert.error_1'));
					if(dialog.select_user_acc.trim().length <= 0)
						return $scope.$root.showAlert($filter('translate')('B0801.js.alert.error_2'));
					if(moment(dialog.select_date_now).format('YYYY-MM-DD').trim().length <= 0)
						return $scope.$root.showAlert($filter('translate')('B0801.js.alert.error_3'));
					if(dialog.select_company_no.trim().length <= 0)
						return $scope.$root.showAlert($filter('translate')('B0801.js.alert.error_4'));
					if(dialog.select_reasion.length <= 0)
						return $scope.$root.showAlert($filter('translate')('B0801.js.alert.error_5'));
					var content = {};
					content.accessory_data = select_data;
					content.reasion_data = dialog.select_reasion;
					content.user_acc =dialog.select_user_acc;
					content.expected_date = moment(dialog.select_date_now).format('YYYY-MM-DD');
					content.company_no = dialog.select_company_no;
					content.description = dialog.select_description;
					$MMWService.sendToServer({
						uri: 'ServicesSTD.Module_ACC.mold_maintenance_process',
						content : content,
						success : function(data){
							$scope.beforeSearch();
							dialog.hide();
							autoPreview(content.accessory_data); // 透過系統參數判斷是否自動預覽維修單
						}
					});
					
				}
			};
			return controller;
		}
		function get_accessory_state_str(type)
		{
			var str ="";
			switch(type)
			{
				case "0":
					str = $filter('translate')('B0801.js.state_list.state_0');
				break;
				case "1":
					str = $filter('translate')('B0801.js.state_list.state_1');
				break;
			}
			return str;
		}
		$scope.select_all_acc_item = function()
		{
			if($scope.acc_data.length <= 0)
				return;
			var select_type = 0;
			if($scope.select_all)
			{
				select_type = 0;
				$scope.select_all = false;
			}
			else
			{
				select_type = 1;
				$scope.select_all = true;
			}
			for(var i in $scope.acc_data)
				$scope.acc_data[i].is_select = select_type;
		}
		$scope.select_acc_item = function(event,item)
		{
			if(item.is_select == 0)
				item.is_select = 1;
			else
				item.is_select = 0;
		}
		$scope.search = function(condition)
		{
			if(condition.length > 0)
			{
				$scope.acc_data = [];
				$scope.select_all = false;
				$scope.is_inject = false;
				var content = {};
				content.query_condition = condition;
				content.query_mode ="0";
				$MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.mold_maintenance_info_get',
                    content : content,
                    success : function(data){
						console.log(data.info_data);
						if(data.info_data.length > 0)
						{
							$scope.is_inject = data.is_inject;
							$scope.acc_data = data.info_data
							for(var i in $scope.acc_data)
							{
								var state = ""+$scope.acc_data[i].accessory_state;
								$scope.acc_data[i].is_select = 0;
								$scope.acc_data[i].state_str =get_accessory_state_str(state);
								if($scope.acc_data[i].combine_acc == "1")
									$scope.acc_data[i].combine_str = $filter('translate')('B0801.js.state_list._1');
								else
									$scope.acc_data[i].combine_str = $filter('translate')('B0801.js.state_list._0');
							}
						}
                    },
                    error_callback:function(data){
                      
                    }
                });
			}
			else
			{
				$scope.$root.showAlert($filter('translate')('B0801.js.alert.error_6'));
			}
		}

		// 透過系統參數判斷是否自動預覽維修單
		function autoPreview(accessory_data){
			$MMWService.pageNumberInfoGet({
				page_mode: 'sys_parameter_info_get_Condition',
				query_condition_info: [
					{column_name: 'PARAMETERTYPE', query_mode: '0', value: 'SysInfo', merge_condition_model: 'AND' },
					{column_name: 'PARAMETERNO', query_mode: '0', value: 'PrintRepairOrderModel', merge_condition_model: 'AND' }
				]
			}, function(itemList){
				if(itemList && itemList.length > 0){
					if(itemList[0].parameter_value === '1'){
						preview(accessory_data);
					}
				}
			});
		}

		// 預覽維修單
		var pdf_url;
		function preview(accessory_data){
			var content = {
				accessory_data: accessory_data
			};
			$MMWService.sendToServer({
				uri: 'ServicesSTD.Module_ACC.mold_runcard_pdf_get',
				content : content,
				success : function(data){

					for(var i = 0; i < content.accessory_data.length; i++){
						$scope.printList.push({
							printNo: content.accessory_data[i].accessory_no,
							printType: '5' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
						});
					}

					if(data.mold_run_card_data && data.mold_run_card_data.length > 0){
						pdf_url = data.mold_run_card_data[0].url_pdf;
						if(pdf_url.indexOf('http://') == -1){
							pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
						}
						if(config.setting.outsidePDF == 'Y'){
							var fs = window.nodeRequire('fs'), RuncardPath;
							try{
								// 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
								const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
								RuncardPath = remote.app.getAppPath();
							}catch(e){
								RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
							}
							RuncardPath += '\\www\\Runcard';
							if(!fs.existsSync(RuncardPath)){
								fs.mkdirSync(RuncardPath);
							}

							// 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
							// 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        	fs.readdirSync(RuncardPath, (err, files) => {
								if (err) {
									console.log(err);
								}
								//listing all files using forEach
								files.forEach((file) => {
									// Do whatever you want to do with the file
									fs.unlink(RuncardPath + '/' + file, (err) => {
										if (err) {
											console.debug(err);
										}
									})
								});
							})
	
							// 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
							let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
							$scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
								// 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
								const { shell } = window.nodeRequire('electron');
								shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
							});
						} else {
							showPDFViewer(pdf_url);
						}
					}
				}
			});
		}

		function showPDFViewer(pdf_url){
			try{
				window.nodeRequire('nw.gui').Window.open(pdf_url, {
					title:'PDF Viewer',
					show: false,
					icon:'icon/icon.png',
					focus:true
				}, function(win) {
					win.on('loaded', function(){
						win.show();
						win.print();
					});
				});
			} catch (e){
				$scope.mode = 'print';
				document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
			}
		}

		// 列印
		$scope.print = function(){
			if(window.nodeRequire){
				var sumatraPDF = window.nodeRequire('sumatra-pdf');
				if(sumatraPDF){
					var fs = window.nodeRequire('fs'), RuncardPath;
					try{
						const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
						RuncardPath = remote.app.getAppPath();
					}catch(e){
						RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
					}
					RuncardPath += '\\www\\Runcard';
					if(!fs.existsSync(RuncardPath)){
						fs.mkdirSync(RuncardPath);
					}

					// 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
					// 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
					fs.readdirSync(RuncardPath, (err, files) => {
						if (err) {
							console.log(err);
						}
						//listing all files using forEach
						files.forEach((file) => {
							// Do whatever you want to do with the file
							fs.unlink(RuncardPath + '/' + file, (err) => {
								if (err) {
									console.debug(err);
								}
							})
						});
					})

					// 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
					let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
					$scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
						$scope.$root.showLoading();
						window.nodeRequire('sumatra-pdf').printWithSettings({
							path: dist_path,
							success:function(){
								printWiplogProcess();
								$scope.$root.hideLoading();
								$scope.$root.showToast($filter('translate')('common.msg.success'));
							},
							error:function(error){
								// 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
								printWiplogProcess();
								$scope.$root.hideLoading();
								$scope.$root.showToast($filter('translate')('common.msg.success'));
								//console.error(error);
							}
						});
					});
				} else {
					window.frames['kmi-pdf-panel'].pdf_print();
				}
			} else {
				window.frames['kmi-pdf-panel'].pdf_print();
			}
		};

		// 下載
		$scope.download = function(){
			window.frames['kmi-pdf-panel'].pdf_download();
		};

		// 取消
		$scope.cancel = function(){
			$scope.mode = 'query';
			document.getElementById('kmi-pdf-panel').src = '';
			$scope.printList = [];
		};

		// 列印完成後，需把列印詳情回送給後台做記錄
		function printWiplogProcess(){
			$MMWService.sendToServer({
				uri: 'ServicesSTD.Module_SN.print_wiplog_process',
				content : {
					printList: $scope.printList
				},
				success : function(){
					$scope.mode = 'query';
					$scope.printList = [];
				}
			});
		}
		
	}
]});